#include "senderwidget.h"
#include "ui_senderwidget.h"
#include "worker.h"

#include <QStringListModel>
#include <QDebug>

SenderWidget::SenderWidget(QWidget *parent, const QString& devicename)
    : QWidget(parent)
    , ui(new Ui::SenderWidget)
    , name(devicename)
    , worker(new Worker(&destIP))
{
    ui->setupUi(this);
    initState();

    qDebug() << "device name: " << name;
}

SenderWidget::~SenderWidget()
{
    SDL_Quit();

    delete ui;

    if (deviceSearcher != nullptr)
    {
        if (deviceSearcher->joinable())
        {
            deviceSearcher->detach(); // 或者使用 deviceSearcher->join();
        }
        delete deviceSearcher;
        deviceSearcher = nullptr;
    }
}

void SenderWidget::initState()
{
    this->setWindowTitle("Sender");

    SDL_Init(SDL_INIT_VIDEO);
    avdevice_register_all(); //注册所有设备，重要

    worker->videoOutput->setShowHandle((void *)ui->widget->winId());

    if(!deviceSearcher)
        deviceSearcher = new std::thread(&SenderWidget::search, this);
}

void SenderWidget::on_btnShareStart_clicked()
{
    if(destIP == "127.0.0.1")
    {
        ui->label_state->setText("当前正在共享的的目标IP为本地，请选择目标IP");
    }
    else
    {
        QString destName = devicesMap[destIP];
        QString s = "Sharing desktop with: " + destName + "[" + destIP + "].";
        ui->label_state->setText(s);
    }
    worker->doTaskRealStart(); //开始实时传输
}

void SenderWidget::on_btnShareStop_clicked()
{
    ui->label_state->clear();
    worker->doTaskRealStop(); //结束实时传输
}

void SenderWidget::on_listWidget_itemClicked(QListWidgetItem *item)
{
    // 修改destIP
    QString itemText = item->text();
    QString showText;

    // 使用正则表达式提取IP地址
    QRegularExpression ipRegex(R"((\d{1,3}\.){3}\d{1,3})");
    QRegularExpressionMatch match = ipRegex.match(itemText);

    if (match.hasMatch()) {
        destIP = match.captured(0);
        showText = "destIP=" + destIP;
        ui->label_destIP->setText(showText);
        qDebug() << "Extracted IP:" << destIP;
    } else {
        ui->label_destIP->setText("请选择目标主机");
        qDebug() << "No valid IP address found in the selected item.";
    }
}

void SenderWidget::on_lineEdit_returnPressed()
{
    QString itemText = ui->lineEdit->text();
    QString showText;

    // 使用正则表达式提取IP地址
    QRegularExpression ipRegex(R"((\d{1,3}\.){3}\d{1,3})");
    QRegularExpressionMatch match = ipRegex.match(itemText);
    if (match.hasMatch()) {
        destIP = match.captured(0);
        showText = "destIP=" + destIP;
        ui->label_destIP->setText(showText);
        qDebug() << "Extracted IP:" << destIP;
    } else {
        ui->label_destIP->setText("请输入正确的目标主机");
        qDebug() << "No valid IP address found in the selected item.";
    }
}


void SenderWidget::search()
{
    //获取局域网中的UDP包
    QUdpSocket udpSocket;
    if (!udpSocket.bind(QHostAddress::Any, 8557)) {
        qDebug() << "Failed to bind socket:" << udpSocket.errorString();
        return;
    }

    while(true)
    {
        while (udpSocket.hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udpSocket.pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;

            udpSocket.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

            // 获取标准的IPv4地址
            QString senderAddress = sender.toString();
            if (senderAddress.startsWith("::ffff:")) {
                senderAddress = senderAddress.section("::ffff:", 1, 1);
            }
            // 获取用户昵称
            QString senderName = QString::fromUtf8(datagram);

            qDebug() << "Received from" << senderAddress << ":" << senderPort;
            qDebug() << "Data:" << senderName;

            QString s = QString::fromUtf8(datagram) + " [" + senderAddress + "]";

            if(!devicesMap.count(senderAddress))
            {
                QListWidgetItem *item1 = new QListWidgetItem(s);
                ui->listWidget->addItem(item1);
                devicesMap.insert({senderAddress, senderName});
            }
        }
        QThread::sleep(5);
    }
}


